{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container-fluid">
        <!-- 面板 -->
        <div class="panel panel-default" style="margin-top: 20px;">
            <!-- Default panel contents -->
            <div class="panel-heading">
                <div>
                    <a href="{% url 'file'  project_id=request.tracer.project.id %}">
                        <i class="fa fa-home" aria-hidden="true"></i>
                        <span>文件库</span>
                    </a>
                    {% for record in parent_list %}
                        <a href="{% url 'file'  project_id=request.tracer.project.id %}?folder={{ record.id }}">
                            <i class="fa fa-caret-right" aria-hidden="true"></i>
                            <span>{{ record.name }}</span>
                        </a>
                    {% endfor %}

                </div>
                <div class="function">
                    <div class="btn btn-primary btn-xs upload" style="position: relative">
                        <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal"
                       data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>

                </div>
            </div>
            <!-- Table -->
            <table class="table">
                <thead>
                <tr>
                    <th>名称</th>
                    <th>文件大小</th>
                    <th>更新者</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                <tbody id="rowList">
                {% for item in file_object_list %}
                    <tr>
                        <td>
                            {% if item.file_type == 2 %}
                                <i class="fa fa-folder" aria-hidden="true"></i>
                                <a href="{% url 'file'  project_id=request.tracer.project.id %}?folder={{ item.id }}">{{ item.name }}</a>
                            {% else %}
                                <i class="fa fa-folder" aria-hidden="true"></i>
                                {{ item.name }}
                            {% endif %}
                        </td>
                        <td>
                            {% if item.file_type == 1 %}
                                {{ item.file_size }}
                            {% else %}
                                -
                            {% endif %}
                        </td>
                        <td>{{ item.update_user.username }}</td>
                        <td>{{ item.update_time }}</td>
                        <td>
                            {% if item.file_type == 2 %}
                                <a class="btn btn-default btn-xs" data-toggle="modal" data-target="#addModal"
                                   data-whatever="修改文件夹"
                                   data-name="{{ item.name }}"
                                   data-fid="{{ item.id }}">
                                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                                    编辑
                                </a>
                            {% else %}
                                <a class="btn btn-default btn-xs download"
                                   href="{% url 'file_download' project_id=request.tracer.project.id file_id=item.id %}">
                                    <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
                                </a>
                            {% endif %}
                            <a class="btn btn-danger btn-xs"
                               data-toggle="modal"
                               data-target="#alertModal"
                               data-fid="{{ item.id }}">
                                <i class="fa fa-trash" aria-hidden="true"></i>
                                删除
                            </a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
                </thead>
            </table>
        </div>
    </div>

    {# 新建文件夹模态框#}
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">新建文件夹</h4>
                </div>
                <div class="modal-body">
                    <form id="form">
                        {% csrf_token %}
                        <input class="hide" type="text" name="fid" id="fid">
                        {% for field in form %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <span class="error-msg">{{ field.errors.0 }}</span>
                            </div>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id='btnFormSubmit' type="button" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 模态框 -->
    {# 警告框#}
    <div class="modal fade" id="alertModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>是否要确定删除？</h4>
                <p style="padding-top: 20px;padding-bottom: 20px;">
                    文件夹中包含的所有的文件都会被删除。
                </p>
                <p style="text-align: right;">
                    <a class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                    <!--在后端实现删除功能代码-->
                    {#                     {% for item in file_object_list %}#}
                    {#                    <button id="btnDelete" type="button" class="btn btn-danger btn-sm"#}
                    {#                            onclick="window.location.href='{% url 'file_delete' project_id=request.tracer.project.id file_id=item.id %}'">#}
                    {#                        确 定#}
                    {#                    </button>#}
                    {#                    {% endfor %}#}
                    <button id="btnDelete" type="button" class="btn btn-danger btn-sm">
                        确 定
                    </button>
                </p>
            </div>
        </div>
    </div>

    <!--进度条-->
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度
            </div>

            <table class="table">
                <tbody id="progressList">
                </tbody>
            </table>
        </div>
    </div>

    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100" style="width: 0%;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>

    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="username"></td>
                <td class="datetime"></td>
                <td>
                    <a class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
                    </a>
                    <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#alertModal">
                        <i class="fa fa-trash" aria-hidden="true"></i> 删除
                    </a>
                </td>
            </tr>
        </table>
    </div>




{% endblock %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FOLDER_URL = "{% url 'file'  project_id=request.tracer.project.id %}"
        var FILE_DELETE_URL = "{% url 'file_delete'  project_id=request.tracer.project.id %}"
        var COS_CREDENTIAL = "{% url 'cos_credential'  project_id=request.tracer.project.id %}"
        /**var COS_OBJECT = new COS({
         getAuthorization: function (options, callback) {
         $.post(COS_CREDENTIAL, {
         data: {name: 666}
         }, function (data) {
         var credentials = data && data.credentials;
         if (!data || !credentials) return console.error('credentials invalid');
         callback({
         TmpSecretId: credentials.tmpSecretId,
         TmpSecretKey: credentials.tmpSecretKey,
         XCosSecurityToken: credentials.sessionToken,
         StartTime: data.startTime,
         ExpiredTime: data.expiredTime,
         });
         });
         }
         });**/
        var FILE_POST = "{% url 'file_post'  project_id=request.tracer.project.id %}"
        var CURRENT_FOLDER_ID = "{{ folder_object.id }}"


        $(function () {
            initAddModal();
            bindModalSubmit();
            bindDeleteSubmit();
            bindUploadFile()
        })

        //模态框
        function initAddModal() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget)
                var recipient = button.data('whatever')
                var modal = $(this)
                var name = button.data('name')
                var fid = button.data('fid')
                modal.find('.modal-title').text(recipient)
                if (fid) {
                    //编辑
                    modal.find('#id_name').val(name);
                    modal.find('#fid').val(fid);
                } else {
                    //新建
                    modal.find('.error_msg').empty()
                    $('form')[0].reset()
                }

            })
            $('#alertModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // 触发模态框的按钮
                var fid = button.data('fid'); // 获取 data-fid 的值
                console.log('FID:', fid);
                $("#btnDelete").attr('fid', fid);// 将 fid 赋值给确认按钮
                var fidSet = $("#btnDelete").attr('fid');
                console.log("fid set to button:", fidSet);

            });
        }

        //新建和编辑操作
        function bindModalSubmit() {
            $('#btnFormSubmit').click(function () {
                $.ajax({
                    url: location.href,
                    type: 'POST',
                    data: $("#form").serialize(),
                    dataType: 'JSON',
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href;
                        } else {
                            $.each(res.error, function (key, value) {
                                $("#id_" + key).next().text(value[0]);
                            })
                        }
                    }

                })
            })
        }

        //删除文件/文件夹

        function bindDeleteSubmit() {
            $('#btnDelete').click(function () {
                var fid = $(this).attr('fid'); // 获取 data-fid 属性
                if (!fid) {
                    alert('无法获取文件ID，请刷新页面后重试。');
                    return;
                }

                // 发送删除请求
                $.ajax({
                    url: FILE_DELETE_URL,
                    type: "GET",
                    data: {fid: fid},
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href;// 删除成功后刷新页面
                        } else {
                            alert('删除失败：' + res.error);
                        }
                    }
                });
            });
        }

        //上传文件
        function bindUploadFile() {
            $("#uploadFile").change(function () {
                    $('#progressList').empty();
                    var checkFileList = [];
                    var file_list = $(this)[0].files;
                    //每次上传时清空
                    //$('#uploadProgress').empty();
                    //生成上传列表
                    $.each(file_list, function (index, fileObject) {
                        var fileName = fileObject.name;
                        var fileSize = fileObject.size;
                        checkFileList.push({'name': fileObject.name, 'size': fileObject.size});
                    });
                    //后台做校验，如果没有问题发送临时凭证，有问题返回错误信息
                    var cos_credential = new COS({
                        getAuthorization: function (options, callback) {
                            //$.post(url,data,callback)
                            $.post(COS_CREDENTIAL, JSON.stringify(checkFileList),
                                //data: {name: file_list}列表套字典，前端无法用request.post.get显示，需要解析
                                //data:JSON.stringify(checkFileList)这样前端传到后台的为序列化后的数据
                                function (res) {
                                    if (res.status) {
                                        var credentials = res.data && res.data.credentials;
                                        //if (!res.data || !credentials) return console.error('credentials invalid');
                                        callback({
                                            TmpSecretId: credentials.tmpSecretId,
                                            TmpSecretKey: credentials.tmpSecretKey,
                                            XCosSecurityToken: credentials.sessionToken,
                                            StartTime: res.data.startTime,
                                            ExpiredTime: res.data.expiredTime,
                                        });
                                        //在上传时显示进度条
                                        $('#uploadProgress').removeClass('hide');
                                    } else {
                                        alert(res.error);
                                    }
                                });
                        }
                    });
                    //  var totalFiles = file_list.length; // 总文件数
                    //var completedCount = 0;
                    //上传文件
                    $.each(file_list, function (index, fileObject) {
                        var fileName = fileObject.name;
                        var fileSize = fileObject.size;
                        var fileKey = (new Date()).getTime() + '_' + fileName

                        //复制id = progressTemplate的tr的内容，然后把文件名传到name中，再将它加入到progresslist中，这样可以实现每次上传文件的进度条功能，而且不要每次都生成tr
                        var tr = $('#progressTemplate').find('tr').clone();

                        /*在JavaScript或jQuery中，tr.find('.name') 是用来查找表格行 (tr) 中具有 class="name" 的元素。
                        .name 是一个CSS选择器，表示选择所有带有 name 类的元素。
                        如果你直接写 name 而不是 .name，JavaScript或jQuery会将其解释为标签名 <name>，而不是类名。
                        因此，tr.find('name') 会查找 <name> 标签，而不是带有 class="name" 的元素。
                         */

                        tr.find('.name').text(fileName);
                        $('#progressList').append(tr);

                        cos_credential.putObject({
                            Bucket: '{{ request.tracer.project.bucket }}',
                            Region: '{{ request.tracer.project.region }}',
                            Key: fileKey,
                            Body: fileObject, // 上传文件对象
                            //显示进度条的进度
                            onProgress: function (progressData) {
                                var percent = progressData.percent * 100 + '%';
                                //动态显示进度条
                                tr.find('.progress-bar').text(percent);
                                tr.find('.progress-bar').css('width', percent)

                            }
                        }, function (err, data) {

                            //console.log(err || data);
                            if (data && data.statusCode === 200) {
                                //上传成功将文件提交到后台并写入数据库
                                $.post(FILE_POST, {
                                        name: fileName,
                                        key: fileKey,
                                        file_size: fileSize,
                                        parent: CURRENT_FOLDER_ID,
                                        etag: data.ETag,
                                        file_path: data.Location,
                                    },
                                    function (res) {
                                        //将上传的文件在页面展示出来
                                        var newTr = $('#rowTpl').find('tr').clone();
                                        newTr.find('.name').text(res.data.name);
                                        newTr.find('.file_size').text(res.data.file_size);
                                        newTr.find('.username').text(res.data.username);
                                        newTr.find('.datetime').text(res.data.datetime);
                                        newTr.find('.delete').attr('data-fid', res.data.id);
                                        newTr.find('.download').attr('href', res.data.download_url);
                                        $('#rowList').append(newTr);

                                        // 自己的进度删除
                                        tr.remove();

                                    })


                            } else {
                                tr.find('.progress-error').text('上传失败')
                            }
                            /** 隐藏当前文件的进度条
                             每次上传完成后增加计数器
                             completedCount++;

                             // 如果所有文件都上传完成，隐藏进度条
                             if (completedCount === file_list.length) {
                             $('#uploadProgress').addClass('hide');

                             }**/

                        });

                    })
                }
            )
        }

    </script>

{% endblock %}